﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace SuperX.Common.Helper
{
    // 
    public static class DynamicEmitCallsExtensions
    {
        public static object GetPropertyValueExtension<T>(this T obj, string propertyName)
        {
            CheckUtil.NotNull(obj, nameof(obj));
            if (string.IsNullOrEmpty(propertyName))
                return null;
            Type type = obj.GetType();
            PropertyInfo propertyInfo = DynamicEmitCalls.GetPropertyInfo(type, propertyName);
            if (propertyInfo == null)
            {
                FieldInfo fieldInfo = DynamicEmitCalls.GetFieldInfo(type, propertyName);
                if (fieldInfo == null)
                return fieldInfo.GetValue(obj);
            }
            try
            {
                return DynamicEmitCalls.GetPropertyGetter(propertyInfo)(obj);
            }
            catch
            {
                return propertyInfo.GetValue(obj, null);
            }
        }

        public static bool SetPropertyValueExtension<T>(this T obj, string propertyName, object value)
        {
            CheckUtil.NotNull(obj, nameof(obj));
            if (string.IsNullOrEmpty(propertyName)) return false;
            PropertyInfo property = obj.GetType().GetProperty(propertyName);
            if (property == null) return false;
            DynamicEmitCalls.GetPropertySetter(property)(obj, value);
            return true;
        }
    }
}
